<script lang="tsx">
import { defineComponent, ref, watchEffect } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { $t } from '@vben/locales';
import { usePage } from '#/hooks/page/usePage';
import { getNewsMgrListApi, updateStatusNewsApi, deleteNewsApi } from '#/api/competition/news-mgr';
import { getMatchListApi, getGroupListApi } from '#/api/competition/registration-info';
import { Pencil, Send, Ban, Trash2 } from '@vben/icons';
import { formatNumberWithCommas } from '#/utils/formatNumber';
import EditNewsMgr from './modules/news-mgr/edit-news-mgr.vue';

export default defineComponent({
  name: 'NewsMgr',
  setup() {
    const newsInfo = ref<any>({});
    const editNewsMgr = ref(false);
    const matchList = ref<any[]>([]);
    const groupList = ref<any[]>([]);
    const moduleList = ref<any[]>([
      { label: $t('competition.newsMgr.module.1'), value: 1 },
      { label: $t('competition.newsMgr.module.2'), value: 2 },
    ]);
    const publishStatusList = ref<any[]>([
      { label: $t('competition.newsMgr.unpublished'), value: false },
      { label: $t('competition.newsMgr.published'), value: true },
    ]);
    // 获取大赛列表
    const loadMatchList = async () => {
      try {
        const response = await getMatchListApi();
        matchList.value = response || [];
      } catch (error) {
      }
    };

    // 获取赛事组别列表
    const loadGroupList = async (compId: string) => {
      if (!compId) {
        groupList.value = [];
        return;
      }
      try {
        const response = await getGroupListApi({
          compId,
          curPage: 1,
        });
        console.log(response);
        groupList.value = response.data || [];
      } catch (error) {
      }
    };

    // 初始化加载大赛列表
    loadMatchList();

    // API配置
    const API = {
      get: (data: any) => {
        let params = { ...data };
        return getNewsMgrListApi(params);
      }
    };

    // 查询配置
    const queryColumns = ref([
      {
        prop: 'subject',
        label: $t('competition.newsMgr.newsTitle'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('competition.newsMgr.newsTitle')]),
      },
      {
        prop: 'compId',
        label: $t('competition.newsMgr.belongCompetition'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.newsMgr.belongCompetition')]),
        options: [],
        onChange: (value: string) => {
          loadGroupList(value);
        }
      },
      {
        prop: 'groupId',
        label: $t('competition.newsMgr.belongGroup'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.newsMgr.belongGroup')]),
        options: [],
      },
      {
        prop: 'module',
        label: $t('competition.newsMgr.newsType'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.newsMgr.newsType')]),
        options: moduleList.value,
      },
      {
        prop: 'publishStatus',
        label: $t('competition.newsMgr.publishStatus'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('competition.newsMgr.publishStatus')]),
        options: publishStatusList.value,
      },
    ]);

    // 监听 matchList 变化，更新查询配置中的选项
    watchEffect(() => {
      if (queryColumns.value[1]) {
        queryColumns.value[1].options = matchList.value.map(item => ({
          label: item.matchName,
          value: item.id
        }));
      }
      if (queryColumns.value[2]) {
        queryColumns.value[2].options = groupList.value.map(item => ({
          label: item.name,
          value: item.id
        }));
      }
    });

    // 表格列配置
    const columns = [
      {
        type: 'index',
        label: $t('common.numberIdxTxt'),
        width: 60,
        align: 'center',
        prop: 'index'
      },
      {
        prop: 'subject',
        label: $t('competition.newsMgr.newsTitle'),
        minWidth: 200,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.subject || '--';
        }
      },
      {
        prop: 'compName',
        label: $t('competition.newsMgr.belongCompetition'),
        minWidth: 120,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.compName || '--';
        }
      },
      {
        prop: 'groupName',
        label: $t('competition.newsMgr.belongGroup'),
        minWidth: 120,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return row.groupName || '--';
        }
      },
      {
        prop: 'module',
        label: $t('competition.newsMgr.newsType'),
        minWidth: 120,
        showOverflowTooltip: true,
        formatter: (row: any) => {
          return moduleList.value.find(item => item.value === +row.module)?.label || '--';
        }
      },
      {
        prop: 'publishStatus',
        label: $t('competition.newsMgr.publishStatus'),
        minWidth: 100,
        align: 'center',
        formatter: (row: any) => {
          const isPublished = row.publishStatus === 'true';
          return (
            <div class="flex items-center justify-center">
              <div
                class="w-2 h-2 rounded-full mr-2"
                style={{ backgroundColor: isPublished ? '#30A46C' : '#AEAEAE' }}
              ></div>
              <span style={{ color: '#191919' }}>
                {isPublished ? $t('competition.newsMgr.published') : $t('competition.newsMgr.unpublished')}
              </span>
            </div>
          );
        }
      },
      {
        prop: 'visitors',
        label: $t('competition.newsMgr.visitors'),
        minWidth: 100,
        align: 'center',
        formatter: (row: any) => {
          return row.visitors >= 0 ? formatNumberWithCommas(row.visitors) : '--';
        }
      },
      {
        prop: 'views',
        label: $t('competition.newsMgr.views'),
        minWidth: 100,
        align: 'center',
        formatter: (row: any) => {
          return row.views >= 0 ? formatNumberWithCommas(row.views) : '--';
        }
      },
    ];

    // 操作按钮配置
    const commands = [
      {
        key: 'publish',
        type: 'primary',
        width: 60,
        render: (row: any) => {
          return (
            <el-tooltip
              effect="dark"
              content={row.publishStatus === 'true' ? $t('common.fiddenTxt') : $t('common.pushTxt')}
              show-after={600}
              placement="top"
            >
              <el-button icon={row.publishStatus === 'true' ? Ban : Send} link onClick={() => handlePublish(row)}></el-button>
            </el-tooltip>
          );
        }
      },
      {
        key: 'edit',
        type: 'primary',
        width: 60,
        render: (row: any) => (
          
            <el-tooltip
              effect="dark"
              content={$t('common.edit')}
              show-after={600}
              placement="top"
            >
              <el-button link onClick={() => handleEdit(row)}><el-badge offset={[1, -3]} is-dot={!!row.draft}><Pencil class="w-[14px] h-[14px]" /></el-badge></el-button>
            </el-tooltip>
        )
      },
      {
        key: 'delete',
        type: 'danger',
        width: 60,
        render: (row: any) => (
          <el-tooltip
            effect="dark"
            content={$t('common.delete')}
            show-after={600}
            placement="top"
          >
            <el-button icon={Trash2} link onClick={() => handleDelete(row)}></el-button>
          </el-tooltip>
        )
      },
    ];

    // 自定义操作处理
    const handleCommand = (action: string, row: any, index?: number) => {
      switch (action) {
        case 'publish':
          handlePublish(row);
          break;
        case 'edit':
          handleEdit(row);
          break;
        case 'delete':
          handleDelete(row);
          break;
      }
    };

    // 发布处理
    const handlePublish = async (row: any) => {
      try {
        if (row.publishStatus === 'true') {
          await ElMessageBox.confirm($t('competition.newsMgr.publishConfirm'), $t('common.tipTxt'), {
            confirmButtonText: $t('common.submitTxt'),
            cancelButtonText: $t('common.cancelTxt'),
            type: 'warning',
          });
        }
        updateStatusNewsApi({
          id: row.id,
          publishStatus: row.publishStatus === 'true' ? false : true,
        }).then(() => {
          ElMessage.success(row.publishStatus === 'true' ? $t('competition.newsMgr.publishSuccess') : $t('competition.newsMgr.unpublishSuccess'));
          getTableData();
        }).catch(() => {
        });
      } catch (error) {
        // 用户取消
      }
    };

    // 编辑处理
    const handleEdit = (row: any) => {
      editNewsMgr.value = true;
      newsInfo.value = row;
    };

    // 删除处理
    const handleDelete = async (row: any) => {

      try {
        await ElMessageBox.confirm($t('competition.newsMgr.deleteConfirm'), $t('common.tipTxt'), {
          confirmButtonText: $t('common.submitTxt'),
          cancelButtonText: $t('common.cancelTxt'),
          type: 'warning',
        });
        // TODO: 调用删除API
        deleteNewsApi(row.id).then(() => {
          ElMessage.success($t('competition.newsMgr.deleteSuccess'));
          getTableData();
        }).catch(() => {
          ElMessage.error($t('competition.newsMgr.deleteFailed'));
        });
      } catch (error) {
        // 用户取消
      }
    };

    // 新增处理
    const handleAdd = () => {
      editNewsMgr.value = true;
    };

    const { render, getTableData } = usePage({
      API,
      operateProps: {
        fixed: 'right',
      },
      columns,
      queryColumns: queryColumns.value,
      commands,
      handleCommand,
    });

    return () => (
      <div class="news-mgr-page">
        {
          render({
            header: (
              <div class="flex justify-between items-center">
                <div class="flex gap-2">
                  <el-button type="primary" onClick={() => handleAdd()}>{$t('common.addTxt')}</el-button>
                </div>
              </div>
            ),
            table: {
              prefix: () => [] // 覆盖默认的 prefix，不包含 serialColumn
            }
          })
        }
        <EditNewsMgr
          newsInfo={newsInfo.value}
          modelValue={editNewsMgr.value}
          onUpdate:modelValue={(val: boolean) => editNewsMgr.value = val}
          onUpdate:confirm={() => {
            getTableData();
            newsInfo.value = {};
          }}
          onCancel={() => {
            console.log('onCancel');
            newsInfo.value = {};
          }}
        />
      </div>
    );
  }
});
</script>

<style lang="scss" scoped>
.news-mgr-page {}
</style>
